package sy.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;

import sy.model.AppComplaint;
import sy.model.IotParkingOutException;
import sy.model.SysProject;
import sy.model.WYAccount;
import sy.model.WYAccountProjectMapping;
import sy.model.WYUser;
import sy.service.AppBaseServiceI;
import sy.service.AppBusinessServiceI;
import sy.service.AppComplaintServiceI;
import sy.service.WYAccountProjectMappingServiceI;
import sy.service.WYAccountServiceI;
import sy.service.WYBaseServiceI;
import sy.service.WYBusinessServiceI;
import sy.service.WYUserServiceI;
import sy.util.DateUtil;
import sy.util.Encrypt;
import sy.util.ResultJson;
@Service("wyBaseService")
public class WYBaseServiceImpl implements WYBaseServiceI{
	@Autowired
	WYAccountServiceI wyAccountService;
	@Autowired
	AppBaseServiceI appBaseService;
	@Autowired
	WYUserServiceI wyUserService;
	@Autowired
	WYAccountProjectMappingServiceI wyAccountProjectMappingService;
	@Autowired
	AppComplaintServiceI appComplaintService;
	@Autowired
	WYBusinessServiceI wyBusinessService;

	private int judgeToken(String token){
		WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
		if(wyAccount==null){
			return 400;//没有登录
		}
		Date loginTime = wyAccount.getLoginTime();
		if (loginTime == null) {
			return 400;//没有登录
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				long d = DateUtil.differDay(sdf.format(loginTime), sdf.format(new Date()));
				/**
				 * 当前时间跟上一次登录时间大于15天，则token过期
				 */
				if (d>15) {
					return 401;//token已过期
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public ResultJson login(String name, String password) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		WYAccount wyAccount = wyAccountService.getLogin(name, Encrypt.md5(password));
		if (wyAccount!=null) {
			Map<String, Object> params = new HashMap<String, Object>();
			wyAccount.setLoginTime(new Date());
			WYUser wyUser = wyUserService.getWYUserByWYAccountId(wyAccount.getId());
			/*************************获取该账号所拥有的项目******************************/
			List<SysProject> projectList = new ArrayList<SysProject>();
			List<WYAccountProjectMapping> wyAccountProjectMappingList = wyAccountProjectMappingService.listWYAccountProjectMappingByKey(wyAccount.getId());
			for(WYAccountProjectMapping obj : wyAccountProjectMappingList){
				projectList.add(obj.getSysProject());
			}
			params.put("wyUser", wyUser);
			params.put("projectList", projectList);
			resultJson.setErrorCode(200);
			resultJson.setMessage("操作成功");
			resultJson.setState(true);
			resultJson.setResult(params);
		} else {
			resultJson.setErrorCode(113);
			resultJson.setMessage("用户名/密码不正确");
			resultJson.setState(false);
		}
		return resultJson;
	}

	@Override
	public ResultJson logout(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		try {
			wyAccountService.uodateLoginTime(token);
			resultJson.setErrorCode(200);
			resultJson.setMessage("操作成功");
			resultJson.setState(true);
		} catch (Exception e){
			resultJson.setErrorCode(201);
			resultJson.setMessage("系统异常");
			resultJson.setState(false);
		}
		return resultJson;
	}

	@Override
	public ResultJson getVerificatCode(String telephone, String workCode) {
		// TODO Auto-generated method stub
		/**
		 * 先判断工号跟手机号码是否匹配，再获取验证码
		 */
		ResultJson resultJson = new ResultJson();
		WYAccount wyAccount = wyAccountService.getWYAccountByCondition(workCode, telephone);
		if(wyAccount!=null){
			resultJson = appBaseService.getVerificatCode(telephone);
		}else{
			resultJson.setErrorCode(112);
			resultJson.setState(false);
			resultJson.setMessage("工号手机号不匹配");
		}
		return resultJson;
	}

	@Override
	public ResultJson testVerificatCode(String workCode,String telephone, String verificatCode) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		WYAccount wyAccount = wyAccountService.getWYAccountByCondition(workCode, telephone);
		if(wyAccount!=null){
			resultJson = appBaseService.testVerificatCode(telephone, verificatCode);
		}else{
			resultJson.setErrorCode(112);
			resultJson.setState(false);
			resultJson.setMessage("工号手机号不匹配");
		}
		return resultJson;
	}

	@Override
	public ResultJson modifyPassword(String workCode,String password) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		try{
			//wyAccountService.modifyPassword(workCode, Encrypt.md5(password));
			WYAccount wyAccount = wyAccountService.getWYAccountByCondition(workCode, "");
			wyAccount.setPassword(Encrypt.md5(password));
			wyAccount.setIsFirstLogin("n");
			resultJson.setErrorCode(200);
			resultJson.setState(true);
			resultJson.setMessage("更新密码成功");
		}catch(Exception e){
			resultJson.setErrorCode(201);
			resultJson.setState(false);
			resultJson.setMessage("系统异常，操作失败");
		}
		return resultJson;
	}

	@Override
	public ResultJson resetPassword(String token, String password) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			try{
				WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
				wyAccount.setPassword(Encrypt.md5(password));
				resultJson.setErrorCode(200);
				resultJson.setState(true);
				resultJson.setMessage("重置密码成功");
			}catch(Exception e){
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("系统异常，操作失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getWYUserInfo(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			Map<String,Object> params = new HashMap<String, Object>();
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			WYUser wyUser = wyUserService.getWYUserByWYAccountId(wyAccount.getId());
			List<SysProject> projectList = new ArrayList<SysProject>();
			/*List<WYAccountProjectMapping> wyAccountProjectMappingList = wyAccountProjectMappingService.listWYAccountProjectMappingByKey(wyAccount.getId());
			for(WYAccountProjectMapping obj : wyAccountProjectMappingList){
				projectList.add(obj.getSysProject());
			}*/
			params.put("wyUser", wyUser);
			params.put("projectList", projectList);
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setResult(params);
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}

	@Override
	public ResultJson getTipsCount(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			WYAccount wyAccount = wyAccountService.getWYAccountByToken(token);
			Map<String, Object> params = new HashMap<String, Object>();
			//if(wyAccount.getWyRole()!=null && (wyAccount.getWyRole().getCode().contains("AGM") || wyAccount.getWyRole().getCode().contains("projectManager"))){
				/****************************获取停车场异常放行总数********************************/
				ResultJson parkingOutExceptionJson =  wyBusinessService.getParkingOutException(wyAccount.getToken());
				if(parkingOutExceptionJson.getErrorCode()==200){
					//JSONArray arr = (JSONArray) parkingOutExceptionJson.getResult();
					Map<String,Object> map = (Map<String, Object>) parkingOutExceptionJson.getResult();
					params.put("outExceptionAccount", map.get("total"));
				}
				if(parkingOutExceptionJson.getErrorCode()==202){
					params.put("outExceptionAccount", 0);
				}
				
				ResultJson projectCycleAlarmJson =  wyBusinessService.getProjectCycleAlarm("201", "1440", token);
				if(projectCycleAlarmJson.getErrorCode()==200){
					JSONArray arr = (JSONArray) parkingOutExceptionJson.getResult();
					params.put("projectCycleAlarmAccount", arr.size());
				}
				if(projectCycleAlarmJson.getErrorCode()==202){
					params.put("projectCycleAlarmAccount", 0);
				}
				
				/****************************获取安防待处理事件总数********************************/
				List<AppComplaint> notDeal = appComplaintService.getListByStatus("0");
				params.put("securityNotDealNo", notDeal.size());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("count", params);
				resultJson.setErrorCode(200);
				resultJson.setState(true);
				resultJson.setResult(map);
			/*}else{
				resultJson.setErrorCode(115);
				resultJson.setState(true);
				resultJson.setMessage("您没有该权限");
			}*/
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}

}
